//字符串转换对象.
function convertCartStrToObj(cartStr){
	if(!cartStr){
		return {};
	}
	var goods = cartStr.split(":");
	var obj = {};
	for(var i = 0; i < goods.length; i ++){
		var data = goods[i].split(",");
		//以商品的id为健，商品的其他信息为值，这个值也设计为一个对象
		obj[data[0]] = {
			name : data[1],
			price : parseFloat(data[2]),
			num : parseInt(data[3]),
			src : data[4]
		}
	}
	return obj;
}
//字符串转换成对象.
function convertObjToCartStr(obj){
			var cartStr = "";
			//遍历对象
			for(var id in obj){
				if(cartStr){
					cartStr += ":";
				}
				cartStr += id + "," + obj[id].name + "," + obj[id].price + "," + obj[id].num + "," + obj[id].src;
			}
			return cartStr;
}
//alert(document.cookie)
//获取商品信息.
	var cartStr = $.cookie("cart") ? $.cookie("cart") : "";
	console.log(cartStr);
	//如果有这个cookie.将其转换成字符串.
	if(cartStr){
		var cartObj = convertCartStrToObj(cartStr);
//		console.log(cartObj);
		//遍历所有的信息.
		for(var id in cartObj){
			var sp = cartObj[id];
			console.log(cartObj[id]);
			var str = `
					<ul class="cyr" id = "${id}">
						<li><input type="checkbox" name="" id="jian_1" class="jian_1"/></li>
						<li><img src="${sp.src}" alt="" class="wh"/></li>
						<li><a href="###" class="zia">${sp.name}</a></li>
						<li><span class="green"></span><span class="blue"></span><span class="orange"></span></li>
						<li>整箱</li>
						<li id="danjia">￥ ${sp.price}</li>
						<li>
							<div class="shuliang">
								<span class="number">
									购买数量
								</span>
								<span id="jian">-</span>
								<span id="ji">${sp.num}</span>
								<span id="jia">+</span>
							</div>
						</li>
						<li id="zongjia">${sp.num * sp.price}</li>
						<li><a href="javascript:;" class="shanchu">删除</a></li>
					</ul>
					`
					$(str).appendTo(".yzs");
					//
					var num = sp.num;
					$("#jian").click(function(){
						num --;
						if(num == 0){
							num = 1;
						}
						$("#ji").html(num);
						$("#zongjia").html($("#ji").html() * sp.price);
					})
					//加法事件.
					$("#jia").click(function(){
						num ++;	
						$("#ji").html(num);
						$("#zongjia").html($("#ji").html() * sp.price);
					})
					//
					
					console.log($("#ji").html() * sp.price);
		}
		//添加点击事件删除事件.
		$(".shanchu").click(function(){
			//删除页面的物品信息.
			var id = $(".cyr").remove();
			//删除商品的cookie.
			var cartStr = $.cookie("cart") ? $.cookie("cart") : "";
			var cartObj = convertCartStrToObj(cartStr);
			//删除cookie.
			$.removeCookie("cart",{path:'/'});
		})
		
		
			
	}
	
